<template>
  <div class="componentType unifiedBg">
    <div class="page-content">
      <div class="classfiy-menu">
        <div class="search-input">
          <el-input
            v-model="filterText"
            style="margin-right:10px"
            size="mini"
            placeholder="搜索一级目录名称、描述"
            clearable
          />
          <el-button size="mini" type="primary" @click="searchHandle">
            搜索
          </el-button>
        </div>
        <el-scrollbar class="page-scrollbar">
          <el-tree
            :data="treeData"
            node-key="_id"
            :expand-on-click-node="false"
            :highlight-current="true"
            @node-click="treeClickHandle"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <svg-icon icon-class="wenjianjia-color" />
              <el-tooltip
                effect="dark"
                :content="data.classifyDescribe"
                placement="right"
              >
                <span>{{ data.classifyName }}</span>
              </el-tooltip>
            </span>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="table-content">
        <div class="search-input">
          <el-select
            v-model="findRules.searchType"
            size="mini"
            style="width:150px!important"
          >
            <el-option label="文件ID" value="_id"></el-option>
            <el-option label="名称" value="templateName"></el-option>
            <el-option label="描述" value="templateDescribe"></el-option>
          </el-select>
          <el-input
            v-model="findRules.searchKeyword"
            style="margin-right:10px"
            size="mini"
            placeholder="搜索文件ID、名称、描述"
            clearable
          />
          <el-button size="mini" type="primary" @click="searchFileHandle">
            搜索
          </el-button>
        </div>
        <table-box
          ref="pageTable"
          :selected-arry.sync="tableSelected"
          :table-config="tableConfig"
          :show-selection="true"
          :no-request="true"
          :other-filters="otherFilters"
          table-default-expand-all
          @btnOperate="btnOperate"
          @row-click="rowClickHandel"
          @selection-change="selectionChangeHandel"
        >
          <el-table-column
            width="1"
            slot="before"
            type="expand"
            :resizable="false"
          >
            <template v-slot="{ row }">
              <div class="expand-content">
                <div
                  class="file-list"
                  v-for="(item, index) in row.fileList"
                  :key="index"
                >
                  <span>
                    {{ item.version }}
                    <span :class="item.isNewest ? 'newest' : ''">
                      {{ item.isNewest ? "（最新版本）" : "" }}
                    </span>
                  </span>
                  <span>{{ item.remark }}</span>
                  <span>{{ item.lastUpdateTime }}</span>
                  <span>
                    <el-button
                      size="mini"
                      type="text"
                      @click="viewHandle(row, item.version)"
                    >
                      预览
                    </el-button>
                    <el-button
                      size="mini"
                      type="text"
                      @click="downloadHandle(row, item.version)"
                    >
                      下载
                    </el-button>
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            slot="before"
            label="序号"
            type="index"
            width="60"
            :resizable="false"
          />
          <el-table-column
            label="名称、版本号"
            prop="templateName"
            min-width="120"
            :resizable="false"
          />
          <el-table-column
            label="描述、版本备注"
            prop="templateDescribe"
            min-width="120"
            :resizable="false"
          />
          <el-table-column
            label="上传时间"
            prop="lastUpdateTime"
            min-width="120"
            :resizable="false"
          />
          <el-table-column label="操作" min-width="120" :resizable="false">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click.stop="copyHandle(row)">
                复制最新模板地址
              </el-button>
            </template>
          </el-table-column>
        </table-box>
      </div>
    </div>
    <!-- 新增/编辑目录 -->
    <el-dialog
      width="500px"
      :title="editDlg.formTitle"
      :visible.sync="editDlg.show"
      append-to-body
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form
        ref="editForm"
        label-width="110px"
        size="mini"
        :model="editDlg.form"
        :rules="editDlg.rules"
      >
        <el-row :gutter="20">
          <el-col v-if="editDlg.formType === 'addChild'" :span="22">
            <el-form-item label="父级目录名称">
              <el-input
                v-model.trim="currentSelectTreeNode.data.classifyName"
                maxlength="50"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col v-if="editDlg.formType === 'addChild'" :span="22">
            <el-form-item label="父级目录描述">
              <el-input
                v-model.trim="currentSelectTreeNode.data.classifyDescribe"
                maxlength="50"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="目录名称" prop="classifyName">
              <el-input
                v-model.trim="editDlg.form.classifyName"
                placeholder="请输入目录名称"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="目录描述" prop="classifyDescribe">
              <el-input
                v-model.trim="editDlg.form.classifyDescribe"
                placeholder="请输入目录描述"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editDlg.show = false">取 消</el-button>
        <el-button
          :loading="editDlg.saveLoading"
          size="mini"
          type="primary"
          @click="submitHandle"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 文件上传 -->
    <el-dialog
      width="500px"
      :title="uploadForm.formTitle"
      :visible.sync="uploadForm.show"
      append-to-body
      :close-on-click-modal="false"
      @close="resetUploadForm"
    >
      <el-form
        ref="uploadForm"
        label-width="110px"
        size="mini"
        :model="uploadForm.form"
        :rules="uploadForm.rules"
      >
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item label="目录名称">
              <el-input :value="classifyAllInfo.name" maxlength="50" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="目录描述">
              <el-input
                :value="classifyAllInfo.describe"
                maxlength="50"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="模板名称" prop="templateName">
              <el-input
                v-model="uploadForm.form.templateName"
                :disabled="uploadForm.formType === 'update'"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="模板描述" prop="templateDescribe">
              <el-input
                v-model="uploadForm.form.templateDescribe"
                :disabled="uploadForm.formType === 'update'"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="版本备注" prop="remark">
              <el-input v-model="uploadForm.form.remark" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="选择模板" prop="templateUrl">
              <el-upload
                ref="templateUpload"
                class="upload-demo"
                :limit="1"
                :auto-upload="false"
                :show-file-list="true"
                accept=".grf"
                :on-change="templateUploadChange"
                :on-remove="templateUploadRemove"
              >
                <el-button size="mini" type="primary">扫 描</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="模板数据">
              <el-upload
                ref="dataUpload"
                class="upload-demo"
                :limit="1"
                :auto-upload="false"
                :show-file-list="true"
                accept=".json"
                :on-change="dataUploadChange"
                :on-remove="dataUploadRemove"
              >
                <el-button size="mini" type="primary">扫 描</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="uploadForm.show = false">
          取 消
        </el-button>
        <el-button
          :loading="uploadForm.saveLoading"
          size="mini"
          type="primary"
          @click="uploadFormSubmitHandle"
        >
          {{ uploadForm.formType === "upload" ? "确认新建" : "确认更新" }}
        </el-button>
      </span>
    </el-dialog>
    <!-- 版本恢复 -->
    <el-dialog
      width="500px"
      title="版本恢复"
      :visible.sync="updateForm.show"
      append-to-body
      :close-on-click-modal="false"
      @close="resetUpdateForm"
    >
      <el-form
        ref="updateForm"
        label-width="130px"
        size="mini"
        :model="updateForm.form"
        :rules="updateForm.rules"
      >
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item label="目录名称">
              <el-input :value="classifyAllInfo.name" maxlength="50" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="目录描述">
              <el-input
                :value="classifyAllInfo.describe"
                maxlength="50"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="模板名称" prop="templateName">
              <el-input
                v-model="updateForm.form.templateName"
                disabled
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="模板描述" prop="templateDescribe">
              <el-input
                v-model="updateForm.form.templateDescribe"
                disabled
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="正在使用的版本" prop="version">
              <el-input
                v-model="updateForm.form.version"
                maxlength="50"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="正在使用的版本备注" prop="remark">
              <el-input
                v-model="updateForm.form.remark"
                maxlength="50"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="需恢复的版本" prop="versionNo">
              <el-select
                v-model="updateForm.form.versionNo"
                placeholder="请选择需恢复的版本"
              >
                <el-tooltip
                  effect="dark"
                  :content="item.remark"
                  placement="right"
                  v-for="(item, index) in updateForm.form.versionList"
                  :key="index"
                >
                  <el-option :label="item.version" :value="item.version">
                  </el-option>
                </el-tooltip>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="updateForm.show = false">
          取 消
        </el-button>
        <el-button
          :loading="updateForm.saveLoading"
          size="mini"
          type="primary"
          @click="swichVersionHandle"
        >
          确认恢复
        </el-button>
      </span>
    </el-dialog>
    <!-- 版本恢复 -->
    <el-dialog
      width="700px"
      title="删除模板"
      top="5vh"
      :visible.sync="dialogDelete.show"
      append-to-body
      :close-on-click-modal="false"
      @close="resetDialogDelete"
    >
      <el-form v-if="tableSelected.length" label-width="100px" size="mini">
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item label="所属目录名称">
              <el-input :value="tableSelected[0].classifyAllName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="所属目录描述">
              <el-input
                :value="tableSelected[0].classifyAllDescribe"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="模板名称">
              <el-input :value="tableSelected[0].templateName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="模板描述">
              <el-input :value="tableSelected[0].templateDescribe" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        v-if="tableSelected.length"
        style="width: 100%"
        :data="tableSelected[0].fileList"
        header-row-class-name="table-list-header"
        max-height="300px"
        border
        @selection-change="deleteSelectHandle"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" />
        <el-table-column label="版本号" min-width="100" prop="version">
          <template v-slot="{ row }">
            <span>{{ row.version }}</span>
            <span v-if="row.isNewest" style="color: #3DC094;">最新版版</span>
          </template>
        </el-table-column>
        <el-table-column label="版本描述" min-width="100" prop="remark" />
        <el-table-column
          label="上传时间"
          min-width="100"
          prop="lastUpdateTime"
        />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogDelete.show = false">
          取 消
        </el-button>
        <el-button
          :loading="dialogDelete.saveLoading"
          size="mini"
          type="primary"
          @click="deleteTemHandle"
        >
          确认删除
        </el-button>
      </span>
    </el-dialog>
    <qup-grid-print
      :title="gridViewTile"
      :visible.sync="showPrintView"
      :template-url="templateUrl"
      :template-data="templateData"
      :show-confirm-btn="false"
    />
  </div>
</template>

<script>
import {
  addClassify,
  findClassifyTree,
  updateClassify,
  deleteClassify,
  saveFile,
  switchVersion,
  fileDownload,
  fileDelete
} from "@/api/template";
import QupGridPrint from "qup-grid-print";
import { createDownload } from "@/utils";
export default {
  name: "TemplateManage",
  components: { QupGridPrint },
  data() {
    const validateclassifyName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入目录名称"));
      } else {
        const regu = /^[A-Za-z0-9-]*$/;
        if (!regu.test(value)) {
          callback(new Error("目录名称必须是英文字母或数字或中划线分割"));
        }
        callback();
      }
    };
    const validatetemplateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入模板名称"));
      } else {
        const regu = /^[A-Za-z0-9_]*$/;
        if (!regu.test(value)) {
          callback(new Error("目录名称必须是英文字母或数字或下划线分割"));
        }
        callback();
      }
    };
    const validateTemplateUrl = (rule, value, callback) => {
      if (!this.templateFile) {
        callback(new Error("请选择上传的模板文件"));
      }
      callback();
    };
    return {
      dialogDelete: {
        show: false,
        saveLoading: false,
        deleteSelected: []
      },
      filterText: "",
      nofilterData: [],
      treeData: [],
      currentSelectTreeNode: null,
      tableSelected: [],
      otherFilters: [],
      tableConfig: {
        hideSettingBtn: true,
        hideSearchBar: true,
        interfacePath: `/api/v1/file/page`,
        pageSize: 10,
        tablePage: [10, 40, 60, 100],
        setting: [],
        btnList:
          process.env.NODE_ENV === "development"
            ? [
                {
                  buttonName: "新增一级目录",
                  optCode: "addFirst",
                  outerFlag: true
                },
                {
                  buttonName: "新增子目录",
                  optCode: "addChild",
                  outerFlag: true
                },
                {
                  buttonName: "新建文件",
                  optCode: "upload",
                  outerFlag: true
                },
                {
                  buttonName: "更新版本",
                  optCode: "update",
                  icon: "",
                  outerFlag: false
                },
                {
                  buttonName: "恢复版本",
                  optCode: "recovery",
                  icon: "",
                  outerFlag: false
                },
                {
                  buttonName: "刷 新",
                  optCode: "refresh",
                  icon: "",
                  outerFlag: true
                },
                {
                  buttonName: "修改目录",
                  optCode: "edit",
                  outerFlag: false
                },
                {
                  buttonName: "删除目录",
                  optCode: "delete",
                  outerFlag: false
                },
                {
                  buttonName: "删除模板",
                  optCode: "deleteTemp",
                  icon: "",
                  outerFlag: false
                }
              ]
            : []
      },
      editDlg: {
        formType: "",
        formTitle: "",
        saveLoading: false,
        show: false,
        form: {
          classifyName: null,
          classifyDescribe: null
        },
        rules: {
          classifyName: [
            {
              required: true,
              validator: validateclassifyName,
              trigger: "blur"
            }
          ],
          classifyDescribe: [
            {
              required: true,
              message: "请输入目录描述"
            }
          ]
        }
      },
      uploadForm: {
        formType: "",
        formTitle: "文件上传",
        saveLoading: false,
        show: false,
        form: {
          templateName: null,
          templateDescribe: null,
          remark: null,
          templateUrl: null,
          templateData: null
        },
        rules: {
          templateName: [
            {
              required: true,
              validator: validatetemplateName,
              trigger: "blur"
            }
          ],
          templateDescribe: [
            {
              required: true,
              message: "请输入模板描述",
              trigger: "blur"
            }
          ],
          templateUrl: [
            {
              required: true,
              validator: validateTemplateUrl,
              trigger: "change"
            }
          ]
        }
      },
      updateForm: {
        formType: "",
        formTitle: "恢复版本",
        saveLoading: false,
        show: false,
        form: {
          _id: null,
          templateName: null,
          templateDescribe: null,
          version: null,
          remark: null,
          versionNo: null,
          versionList: []
        },
        rules: {
          versionNo: [
            {
              required: true,
              message: "请选择需要恢复的版本",
              trigger: "change"
            }
          ]
        }
      },
      templateFile: null, // 选择的模板文件
      dataFile: null, // 选择的json文件
      findRules: {
        searchType: "_id",
        searchKeyword: ""
      },
      showPrintView: false,
      templateUrl: "",
      templateData: "",
      gridViewTile: "",
      classifyAllInfo: {
        name: "",
        describe: ""
      }
    };
  },
  //   computed: {
  //     uploadPath() {
  //       if (
  //         this.currentSelectTreeNode &&
  //         this.currentSelectTreeNode.level === 1
  //       ) {
  //         return {
  //           path: this.currentSelectTreeNode.data.classifyName,
  //           name: this.currentSelectTreeNode.data.classifyDescribe
  //         };
  //       }
  //       if (
  //         this.currentSelectTreeNode &&
  //         this.currentSelectTreeNode.level === 2
  //       ) {
  //         return {
  //           path: `${this.currentSelectTreeNode.parent.data.classifyName}/${
  //             this.currentSelectTreeNode.data.classifyName
  //           }`,
  //           name: `${this.currentSelectTreeNode.parent.data.classifyDescribe}/${
  //             this.currentSelectTreeNode.data.classifyDescribe
  //           }`
  //         };
  //       }
  //       return "";
  //     }
  //   },
  mounted() {
    this.findClassifyTree();
    this.findTamplatePage();
  },
  methods: {
    // 删除选择
    deleteSelectHandle(list) {
      this.dialogDelete.deleteSelected = list;
    },
    // 删除表单重置
    resetDialogDelete() {
      this.dialogDelete = {
        show: false,
        saveLoading: false,
        deleteSelected: []
      };
    },
    // 删除确认
    deleteTemHandle() {
      if (!this.dialogDelete.deleteSelected.length) {
        this.$message.warning("请选择需要删除的版本");
        return;
      }
      if (
        this.dialogDelete.deleteSelected.length ===
        this.tableSelected[0].fileList.length
      ) {
        this.$confirm(
          "是否删除当前文件的所有版本, 删除后当前文件将不能再使用?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            this.deleteConfirmHandle();
          })
          .catch(() => {});
        return;
      }
      const isSelectNew = this.dialogDelete.deleteSelected.find(
        item => item.isNewest
      );
      if (isSelectNew) {
        this.$confirm(
          "当前选中的版本中有正在使用的最新版本, 删除后最新版本将更改为最后上传的版本，是否继续？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            this.deleteConfirmHandle();
          })
          .catch(() => {});
        return;
      }
      this.deleteConfirmHandle();
    },
    // 提交删除
    deleteConfirmHandle() {
      const params = {
        _id: this.tableSelected[0]._id,
        versionNOs: this.dialogDelete.deleteSelected.map(item => item.version)
      };
      fileDelete(params)
        .then(res => {
          this.findTamplatePage();
          this.dialogDelete.show = false;
          this.$message.success("删除成功！");
        })
        .catch(() => {});
    },
    // 查询分类树
    findClassifyTree() {
      findClassifyTree().then(res => {
        this.treeData = res.data;
        this.nofilterData = res.data;
      });
    },
    // 树节点点击
    treeClickHandle(data, node, e) {
      this.currentSelectTreeNode = node;
      this.findRules.searchKeyword = "";

      this.classifyAllInfo.name =
        this.currentSelectTreeNode.level === 1
          ? this.currentSelectTreeNode.data.classifyName
          : `${this.currentSelectTreeNode.parent.data.classifyName}/${
              this.currentSelectTreeNode.data.classifyName
            }`;
      this.classifyAllInfo.describe =
        this.currentSelectTreeNode.level === 1
          ? this.currentSelectTreeNode.data.classifyDescribe
          : `${this.currentSelectTreeNode.parent.data.classifyDescribe}/${
              this.currentSelectTreeNode.data.classifyDescribe
            }`;
      this.findTamplatePage();
    },
    // 本地搜索
    searchHandle() {
      if (!this.filterText) {
        this.treeData = this.nofilterData;
        return;
      }
      this.treeData = this.nofilterData.filter(
        item =>
          item.classifyName.indexOf(this.filterText) !== -1 ||
          item.classifyDescribe.indexOf(this.filterText) !== -1
      );
    },
    // 表格操作按钮
    btnOperate(flag) {
      switch (flag) {
        // 新增一级目录
        case "addFirst":
          this.editDlg.formTitle = "新增一级目录";
          this.editDlg.formType = "addRoot";
          this.editDlg.show = true;
          break;
        // 新增子目录
        case "addChild":
          console.log(this.currentSelectTreeNode);
          if (!this.currentSelectTreeNode) {
            this.$message.warning("请先选中一个父级目录");
            return;
          }
          if (this.currentSelectTreeNode.level !== 1) {
            this.$message.warning("只能在一级目录下新增子目录");
            return;
          }
          this.editDlg.formTitle = "新增子目录";
          this.editDlg.formType = "addChild";
          this.editDlg.show = true;
          break;
        // 修改目录
        case "edit":
          if (!this.currentSelectTreeNode) {
            this.$message.warning("请选中需要修改的目录");
            return;
          }
          this.editDlg.formTitle = "修改目录";
          this.editDlg.formType = "edit";
          this.editDlg.form = {
            classifyName: this.currentSelectTreeNode.data.classifyName,
            classifyDescribe: this.currentSelectTreeNode.data.classifyDescribe
          };
          this.editDlg.show = true;
          break;
        // 删除目录
        case "delete":
          if (!this.currentSelectTreeNode) {
            this.$message.warning("请选中需要删除的目录");
            return;
          }
          console.log(this.currentSelectTreeNode);
          this.$confirm(
            `确认删除[ ${
              this.currentSelectTreeNode.data.classifyName
            } ]目录吗?`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              deleteClassify(this.currentSelectTreeNode.data._id).then(res => {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                if (this.currentSelectTreeNode.level === 1) {
                  const index = this.treeData.findIndex(
                    item => item._id === this.currentSelectTreeNode.data._id
                  );
                  this.treeData.splice(index, 1);
                  return;
                }
                if (this.currentSelectTreeNode.level === 2) {
                  const index = this.currentSelectTreeNode.parent.data.children.findIndex(
                    item => item._id === this.currentSelectTreeNode.data._id
                  );
                  this.currentSelectTreeNode.parent.data.children.splice(
                    index,
                    1
                  );
                  return;
                }
              });
            })
            .catch(() => {});
          break;
        // 上传文件
        case "upload":
          if (!this.currentSelectTreeNode) {
            this.$message.warning("请选中一个目录上传");
            return;
          }
          this.uploadForm.formType = "upload";
          this.uploadForm.formTitle = "新建文件";
          this.uploadForm.show = true;
          break;
        // 刷 新
        case "refresh":
          this.findTamplatePage();
          break;
        // 更新版本
        case "update":
          if (!this.singleJudge(this.tableSelected, "文件更新", true)) {
            return;
          }
          this.uploadForm.formType = "update";
          this.uploadForm.formTitle = "文件更新";
          this.classifyAllInfo = {
            name: this.tableSelected[0].classifyAllName,
            describe: this.tableSelected[0].classifyAllDescribe
          };
          this.uploadForm.form.templateDescribe = this.tableSelected[0].templateDescribe;
          this.uploadForm.form.templateName = this.tableSelected[0].templateName;
          this.uploadForm.show = true;
          console.log(this.tableSelected);
          break;
        // 恢复版本
        case "recovery":
          if (!this.singleJudge(this.tableSelected, "恢复版本", true)) {
            return;
          }
          this.classifyAllInfo = {
            name: this.tableSelected[0].classifyAllName,
            describe: this.tableSelected[0].classifyAllDescribe
          };
          this.updateForm.form._id = this.tableSelected[0]._id;
          this.updateForm.form.templateName = this.tableSelected[0].templateName;
          this.updateForm.form.templateDescribe = this.tableSelected[0].templateDescribe;
          const currentVersionInfo = this.tableSelected[0].fileList.find(
            item => item.isNewest
          );
          this.updateForm.form.version = currentVersionInfo.version;
          this.updateForm.form.remark = currentVersionInfo.remark;
          this.updateForm.form.versionList = this.tableSelected[0].fileList.filter(
            item => !item.isNewest
          );
          this.updateForm.show = true;
          break;
        // 删除模板
        case "deleteTemp":
          if (!this.singleJudge(this.tableSelected, "删除", true)) {
            return;
          }
          this.dialogDelete.show = true;
          break;
      }
    },
    // 主表格点击
    rowClickHandel(data) {
      this.$refs.pageTable.clearSelection();
      this.$refs.pageTable.toggleRowSelection(data.row, true);
    },
    // 复选框操作
    selectionChangeHandel(val) {
      this.tableSelected = val;
    },
    // 新增编辑目录
    submitHandle() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.editDlg.saveLoading = true;
          const data = JSON.parse(JSON.stringify(this.editDlg.form));
          // 修改目录
          if (this.editDlg.formType === "edit") {
            data._id = this.currentSelectTreeNode.data._id;
            updateClassify(data)
              .then(res => {
                this.editDlg.saveLoading = false;
                this.editDlg.show = false;
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.currentSelectTreeNode.data.classifyName =
                  data.classifyName;
                this.currentSelectTreeNode.data.classifyDescribe =
                  data.classifyDescribe;
              })
              .catch(() => {
                this.editDlg.saveLoading = false;
              });
            return;
          }
          //   // 新增一级目录
          //   if (this.editDlg.formType === "addRoot") {

          //   }
          // 新增子目录
          if (this.editDlg.formType === "addChild") {
            data.parent = this.currentSelectTreeNode.data._id;
          }
          addClassify(data)
            .then(res => {
              if (this.editDlg.formType === "addRoot") {
                this.treeData.push(res.data);
              }
              if (this.editDlg.formType === "addChild") {
                const index = this.treeData.findIndex(
                  item => item._id === res.data.parent
                );
                this.treeData[index].children.push(res.data);
              }
              this.editDlg.saveLoading = false;
              this.editDlg.show = false;
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            })
            .catch(err => {
              console.log(err);
              this.editDlg.saveLoading = false;
            });
        }
      });
    },
    // 重置表单
    resetForm() {
      this.editDlg.form = {
        classifyName: null,
        classifyDescribe: null
      };
      const timer = setTimeout(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate();
        clearTimeout(timer);
      }, 0);
    },
    // 获取文件后缀
    getFileType(name) {
      const startIndex = name.lastIndexOf(".");
      if (startIndex !== -1) {
        return name.slice(startIndex + 1).toLowerCase();
      } else {
        return "";
      }
    },
    // 获取文件名
    getFileName(name) {
      const startIndex = name.lastIndexOf(".");
      if (startIndex !== -1) {
        return name.slice(0, startIndex);
      } else {
        return "";
      }
    },
    // 模板选择校验
    templateUploadChange(file, fileList) {
      console.log(file);
      if (file.size / (1024 * 1024) > 10) {
        // 限制文件大小
        this.$message.warning(`当前限制文件大小不能大于10M`);
        this.$refs.templateUpload.clearFiles();
        return;
      }
      const suffix = this.getFileType(file.name); // 获取文件后缀名
      const suffixArray = ["grf"]; // 限制的文件类型，根据情况自己定义
      if (suffixArray.indexOf(suffix) === -1) {
        this.$message({
          message: "只支持上传grf后缀的文件",
          type: "error",
          duration: 2000
        });
        this.$refs.templateUpload.clearFiles();
        return;
      }
      if (this.dataFile) {
        const dataFileName = this.getFileName(this.dataFile.name);
        const templateName = this.getFileName(file.name);
        if (templateName !== dataFileName) {
          this.$message({
            message: "模板文件名称必须与数据文件名称一致",
            type: "error",
            duration: 2000
          });
          this.$refs.templateUpload.clearFiles();
          return;
        }
      }
      this.templateFile = file.raw;
      this.$refs.uploadForm.validate(() => {});
    },
    templateUploadRemove(file, fileList) {
      this.templateFile = null;
    },
    dataUploadRemove(file, fileList) {
      this.dataFile = null;
    },
    // 数据选择校验
    dataUploadChange(file, fileList) {
      console.log(file);
      if (file.size / (1024 * 1024) > 10) {
        // 限制文件大小
        this.$message.warning(`当前限制文件大小不能大于10M`);
        this.$refs.dataUpload.clearFiles();
        return;
      }
      const suffix = this.getFileType(file.name); // 获取文件后缀名
      const suffixArray = ["json"]; // 限制的文件类型，根据情况自己定义
      if (suffixArray.indexOf(suffix) === -1) {
        this.$message({
          message: "只支持上传json后缀的文件",
          type: "error",
          duration: 2000
        });
        this.$refs.dataUpload.clearFiles();
        return;
      }
      if (this.templateFile) {
        const templateName = this.getFileName(this.templateFile.name);
        const dataFileName = this.getFileName(file.name);
        if (templateName !== dataFileName) {
          this.$message({
            message: "数据文件名称必须与模板文件名称一致",
            type: "error",
            duration: 2000
          });
          this.$refs.dataUpload.clearFiles();
          return;
        }
      }
      this.dataFile = file.raw;
    },
    resetUploadForm() {
      this.uploadForm.form = {
        templateName: null,
        templateDescribe: null,
        remark: null,
        templateUrl: null,
        templateData: null
      };
      this.templateFile = null;
      this.dataFile = null;
      this.$refs.dataUpload.clearFiles();
      this.$refs.templateUpload.clearFiles();
      const timer = setTimeout(() => {
        this.$refs.uploadForm && this.$refs.uploadForm.clearValidate();
        clearTimeout(timer);
      }, 0);
    },
    // 上传、更新
    uploadFormSubmitHandle() {
      this.$refs.uploadForm.validate(async valid => {
        if (valid) {
          const params = {
            templateFile: this.templateFile,
            jsonFile: this.dataFile
          };
          const formData = new FormData();
          Object.keys(params).forEach(key => {
            params[key]
              ? formData.append(key, params[key])
              : delete params[key];
          });
          const data = {
            _id:
              this.uploadForm.formType === "update"
                ? this.tableSelected[0]._id
                : null,
            classifyId:
              this.uploadForm.formType === "update"
                ? this.tableSelected[0].classify
                : this.currentSelectTreeNode.data._id,
            templateName: this.uploadForm.form.templateName,
            templateDescribe: this.uploadForm.form.templateDescribe,
            remark: this.uploadForm.form.remark
          };
          console.log(params, formData);
          const seveRes = await saveFile({ files: formData, data });
          if (seveRes.success) {
            this.$message.success("保存成功");
            this.uploadForm.show = false;
            this.findTamplatePage();
          }
        }
      });
    },
    // 分页查询模板数据
    findTamplatePage() {
      this.otherFilters = [];
      this.$nextTick(() => {
        if (this.currentSelectTreeNode) {
          this.otherFilters.push({
            id: "classify",
            value: this.currentSelectTreeNode.data._id,
            property: "classify",
            operator: "="
          });
        }
        if (this.findRules.searchKeyword) {
          this.otherFilters.push({
            id: this.findRules.searchType,
            value: this.findRules.searchKeyword,
            property: this.findRules.searchType,
            operator: this.findRules.searchType === "_id" ? "=" : "like"
          });
        }
        this.$refs.pageTable.initTableData();
      });
    },
    // 恢复版本
    swichVersionHandle() {
      this.$refs.updateForm.validate(async valid => {
        if (valid) {
          this.updateForm.saveLoading = true;
          switchVersion({
            _id: this.updateForm.form._id,
            versionNo: this.updateForm.form.versionNo
          })
            .then(res => {
              this.updateForm.show = false;
              this.$message.success("操作成功");
              this.findTamplatePage();
              this.updateForm.saveLoading = false;
            })
            .catch(() => {
              this.updateForm.saveLoading = false;
            });
        }
      });
    },
    resetUpdateForm() {
      this.updateForm.form = {
        _id: null,
        templateName: null,
        templateDescribe: null,
        version: null,
        remark: null,
        versionNo: null,
        versionList: []
      };
      const timer = setTimeout(() => {
        this.$refs.updateForm && this.$refs.updateForm.clearValidate();
        clearTimeout(timer);
      }, 0);
    },
    // 预览
    async viewHandle(row, version) {
      //   this.templateUrl = await fileDownload({
      //      fileId: row._id,
      //     versionNo: version,
      //     fileType: "grf"
      //   });
      this.gridViewTile = `目录：[${row.classifyAllName}] 版本：[${version}]`;
      this.templateUrl = `http://127.0.0.1:7001/api/v1/file/download?fileId=${
        row._id
      }&versionNo=${version}`;
      this.templateData = `http://127.0.0.1:7001/api/v1/file/download?fileId=${
        row._id
      }&versionNo=${version}&fileType=json`;
      this.showPrintView = true;
    },
    // 下载
    async downloadHandle(row, version) {
      fileDownload({
        fileId: row._id,
        versionNo: version,
        fileType: "grf"
      })
        .then(res => {
          this.$message.success("操作成功，请等待模板下载");
          createDownload(res, `${version}-${row.templateName}`, "grf");
        })
        .catch(() => {
          this.$message.fail("模板下载失败");
        });

      fileDownload({
        fileId: row._id,
        versionNo: version,
        fileType: "json"
      })
        .then(res => {
          this.$message.success("操作成功，请等待模板数据文件下载");
          createDownload(JSON.stringify(res), `${row.templateName}`, "json");
        })
        .catch(() => {
          this.$message.fail("模板数据文件下载失败");
        });
    },
    copyTocontent(str) {
      const el = document.createElement("textarea");
      el.value = str;
      el.setAttribute("readonly", "");
      el.style.position = "absolute";
      el.style.left = "-9999px";
      document.body.appendChild(el);
      const selected =
        document.getSelection().rangeCount > 0
          ? document.getSelection().getRangeAt(0)
          : false;
      el.select();
      document.execCommand("copy");
      document.body.removeChild(el);
      if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
      }
    },
    // 复制模板地址
    copyHandle(row) {
      this.copyTocontent(
        `http://127.0.0.1:7001/api/v1/file/download?fileId=${row._id}`
      );
      this.$message({
        message: "复制成功",
        type: "success"
      });
    },
    // 搜索文件
    searchFileHandle() {
      this.findTamplatePage();
    }
  }
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100% !important;
}
.componentType {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
}
.header-control-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  border-bottom: 1px solid #eee;

  .header-title {
    font-size: 18px;
    font-weight: bold;
  }
}
.page-content {
  width: 100%;
  height: 100%;
  .classfiy-menu {
    float: left;
    width: 280px;
    height: 100%;
    background-color: #fff;
    border-right: 1px solid #eee;
    padding: 0 14px 20px;
    box-sizing: border-box;
    .search-input {
      display: flex;
      margin-bottom: 10px;
    }
    .custom-tree-node {
      width: 100%;
    }
    /deep/
      .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      background-color: $--color-primary;
      color: #fff;
    }
  }
  .table-content {
    float: left;
    width: calc(100% - 280px);
    height: 100%;
    padding-left: 10px;
    box-sizing: border-box;
    // background-color: pink;
    .search-input {
      position: relative;
      z-index: 2;
      width: 360px;
      display: flex;
      margin-bottom: -33px;
      box-sizing: border-box;
    }
    /deep/ .function-box {
      display: flex;
      justify-content: flex-end;
      padding-left: 350px;
      box-sizing: border-box;
      .last-flex {
        display: none;
      }
    }
    /deep/ .el-table__expand-icon > .el-icon {
      display: none;
    }
    /deep/ .table-list-box .el-table--enable-row-transition .el-table__body td {
      border: 0;
    }
    .expand-content {
      border-bottom: 1px solid #ddd;
      padding-left: 110px;
      box-sizing: border-box;
      .file-list {
        display: flex;
        align-items: center;
        height: 36px;
        border-top: 1px dashed #ddd;
        .newest {
          color: #3dc094;
        }
        > span {
          flex: 1;
          padding-left: 12px;
          box-sizing: border-box;
          color: #888;
        }
      }
    }
  }
}
</style>
